package mo.tags.twopointer;

import java.util.Arrays;

public class L16 {

    public int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE;
        int res = 0;
        Arrays.sort(nums);
        int len = nums.length;
        for (int first = 0; first < len; first++) {
            int third = len - 1;
            int second = first + 1;
            while (second <  third) {
                int cur = nums[first] + nums[second] + nums[third];
                if (cur == target) {
                    return target;
                } else if (cur > target) {
                    third--;
                } else {
                    second++;
                }
                int abs = Math.abs(cur-target);
                if (abs < min) {
                    res = cur;
                    min = Math.min(min, abs);
                }
            }
            if (res > target) {
                break;
            }
        }
        return res;
    }


    //[4,0,5,-5,3,3,0,-4,-5]
    //-2
    public static void main(String[] args) {
        L16 test = new L16();
        System.out.println(test.threeSumClosest(new int[]{4,0,5,-5,3,3,0,-4,-5}, -2));
    }

}
